package com.hdy.net.order;

import android.content.Context;

import com.hdy.common.version.OrderVersionController;
import com.hdy.net.retrofit.BaseInterceptor;
import com.hdy.net.retrofit.CacheInterceptor;
import com.hdy.net.retrofit.NovateCookieManger;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class StartRetrofit {

    private final int DEFAULT_TIMEOUT = 20;
    private final int KEEP_ALIVE_DURATION = 15;
    private final int MAX_IDLE_CONNECTION = 8;
    private static StartRetrofit sStartRetrofit;
    private OkHttpClient sOkHttpClient;

    public static StartRetrofit getInstance() {
        if (sStartRetrofit == null) {
            synchronized (StartRetrofit.class) {
                if (sStartRetrofit == null) {
                    sStartRetrofit = new StartRetrofit();
                }
            }
        }
        return sStartRetrofit;
    }

    public void initOkHttpClient(Context context, Map<String, String> mHeader) {
        if (sOkHttpClient == null) {
            synchronized (StartRetrofit.class) {
                if (sOkHttpClient == null) {
                    Cache cache = new Cache(new File(context.getCacheDir(), "hdy_order_cache"), 10 * 1024 * 1024);
                    sOkHttpClient = new OkHttpClient.Builder()
                        .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                        .cookieJar(new NovateCookieManger(context))
                        .cache(cache)
                        .addInterceptor(new BaseInterceptor(mHeader))
                        .addInterceptor(new CacheInterceptor(context))
                        .addNetworkInterceptor(new CacheInterceptor(context))
                        .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                        .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION, TimeUnit.SECONDS))
                        .build();
                }
            }
        }
    }

    public IRetrofitClient build(String baseUrl, String version) {
        switch (version) {
            case OrderVersionController.VERSION_FOR_DGJ:
                return new DGJRetrofitClient(baseUrl, sOkHttpClient);
            case OrderVersionController.VERSION_FOR_EWH:
                break;
        }
        return new DGJRetrofitClient(baseUrl, sOkHttpClient);
    }
}
